import React, { FC, useEffect, useRef } from 'react';
import Taro, { getCurrentInstance, useRouter } from '@tarojs/taro';
import { View, Canvas, Image } from '@tarojs/components';
import WeCropper from 'we-cropper';
import './index.less';
import store from '@/src/store';
import closeIcon from '../../assert/imgs/vedio/closeIcon.png';

const CropperPage: FC = () => {
  const inst = getCurrentInstance();
  const ecRef = useRef<any>(null); // eventChannel
  const cropperRef = useRef<any>(null); // we-cropper 实例

  const { pixelRatio } = Taro.getSystemInfoSync();
  const router = useRouter();
  const ratio = Number(router.params?.ratio || 16 / 9);

  useEffect(() => {
    ecRef.current = inst.page?.getOpenerEventChannel?.() || null;

    Taro.nextTick(() => {
      // 量取 #cropper 对应 Canvas 的真实尺寸
      Taro.createSelectorQuery()
        .select('#cropper') // 或 .select('.canvas')
        .boundingClientRect((rect: any) => {
          // 有些机型第一次量到 0，高度先用 wrap 的可视高度或 windowHeight
          let stageW = Math.round(rect?.width || 0);
          let stageH = Math.round(rect?.height || 0);
          if (!stageW || !stageH) {
            const { windowWidth, windowHeight } = Taro.getSystemInfoSync();
            stageW = windowWidth;
            stageH = windowHeight; // 足够让 we-cropper 初始化，不再卡住
          }

          let cutW = stageW - 32;
          let cutH = cutW / ratio;
          if (cutH > stageH - 32) {
            cutH = stageH - 32;
            cutW = cutH * ratio;
          }
          const cutX = Math.round((stageW - cutW) / 2);
          const cutY = Math.round((stageH - cutH) / 2);

          const cropper = new WeCropper({
            id: 'cropper',
            width: stageW,
            height: stageH,
            pixelRatio,
            scale: 2.5,
            zoom: 8,
            cut: { x: cutX, y: cutY, width: cutW, height: cutH },
          } as any);

          cropperRef.current = cropper;

          ecRef.current?.on?.('init', ({ src }) => {
            if (!src) return;
            if (/^https?:/.test(src)) {
              Taro.downloadFile({
                url: src,
                success: ({ tempFilePath }) => cropper.pushOrign(tempFilePath),
                fail: () =>
                  Taro.showToast({ title: '图片下载失败', icon: 'none' }),
              });
            } else {
              cropper.pushOrign(src);
            }
          });
        })
        .exec();
    });
  }, []);

  // 1) 事件适配器：用 e 或 e.mp
  const passToCropper =
    (handler: 'touchStart' | 'touchMove' | 'touchEnd') => (e: any) => {
      const ev: any = (e && (e.mp || e)) || {};
      if (!ev.touches || !ev.touches.length) return;
      cropperRef.current?.[handler]?.(ev);
    };

  const onCancel = () => Taro.navigateBack();

  const onConfirm = () => {
    cropperRef.current?.getCropperImage((tempFilePath) => {
      if (!tempFilePath) {
        Taro.showToast({ title: '导出失败', icon: 'none' });
        return;
      }
      ecRef.current?.emit?.('done', { tempFilePath });
      Taro.navigateBack();
    });
  };
  return (
    <View
      className="page"
      catchMove
      style={{ paddingTop: `${store.commonStore.pageAreaTop}rpx` }}
    >
      <View className="custome-title">
        <Image
          src={closeIcon}
          className="custom-icon-left"
          onClick={onCancel}
        ></Image>
        <View className="title">裁剪</View>
        <Image
          src={'https://file.linkcook.cn/image/wineMiniProgram/home/done.png'}
          className="custom-icon-right"
          onClick={onConfirm}
        ></Image>
      </View>
      <View className="canvas-wrap">
        <Canvas
          id="cropper"
          canvasId="cropper"
          className="canvas"
          disableScroll
          onTouchStart={passToCropper('touchStart')}
          onTouchMove={passToCropper('touchMove')}
          onTouchEnd={passToCropper('touchEnd')}
        />
      </View>
    </View>
  );
};

export default CropperPage;
